/*
 * @Author: szx
 * @Date: 2021-11-30 14:16:36
 * @LastEditTime: 2021-12-09 14:29:12
 * @Description:
 * @FilePath: \leetcode\100-199\151\151.js
 */
/**
 * @param {string} s
 * @return {string}
 */
// var reverseWords = function (s) {
//     return s.trim().split(/\s+/).reverse().join(' ');
// };
const removeExtraSpaces = function (strArr) {
    let slowIndex = 0;
    let fastIndex = 0;

    while (fastIndex < strArr.length) {
        // 移除开始位置和重复的空格
        if (strArr[fastIndex] === ' ' && (fastIndex === 0 || strArr[fastIndex - 1] === ' ')) {
            fastIndex++;
        } else {
            strArr[slowIndex++] = strArr[fastIndex++];
        }
    }
    // 移除末尾空格
    strArr.length = strArr[slowIndex - 1] === ' ' ? slowIndex - 1 : slowIndex;
};
const reverse = function (strArr, l, r) {
    while (l < r) {
        [strArr[l], strArr[r]] = [strArr[r], strArr[l]];
        l++;
        r--;
    }
};
var reverseWords = function (s) {
    const arr = Array.from(s);
    removeExtraSpaces(arr);
    reverse(arr, 0, arr.length - 1);
    let l = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == ' ') {
            reverse(arr, l, i - 1);
            l = i + 1;
        }
    }
    reverse(arr, l, arr.length - 1);
    return arr.join('');
};
console.log('1' + reverseWords('  the   sky is   blue  ') + '2');
